/**
 * 
 * @author CYJ
 * 
 */
#define SERVER_ADDRESS "mqtt broker addr"
#define CLIENT_NAME "PC_Stat_Mon"
#define SUB_TOPIC "pc/yourPC/stat"

//----------------------------
#include <ArduinoJson.h>
DynamicJsonDocument doc(1024);

//----------------------------
#include <WiFiManager.h> // WiFi Web config interface

//----------------------------
#include <Wire.h> // OLED relative
#include "SSD1306Wire.h"
#include "font.h"
SSD1306Wire display(0x3c, 4, 5);

//----------------------------
#include "EspMQTTClient.h" // MQTT client

EspMQTTClient client( // MQTT client struct
  SERVER_ADDRESS,   // MQTT Broker server ip
  //"MQTTUsername",   // Can be omitted if not needed
  //"MQTTPassword",   // Can be omitted if not needed
  1883,       // The MQTT port, default to 1883. this line can be omitted
  CLIENT_NAME // Client name that uniquely identify your device
);

//-----------------------------------------------------------
void setup() {
  Serial.begin(115200); // initialize serial

  //pinMode(0, INPUT); // initialize boot reset

  //----------------------------
  display.init();
  display.flipScreenVertically(); // initialize OLED
  //drawBoot();

  //----------------------------
  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  drawConf();

  //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;

  //reset settings - wipe credentials for testing
  //wm.resetSettings();

  // Automatically connect using saved credentials,
  // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"),
  // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
  // then goes into a blocking loop awaiting configuration and will return success result

  bool res;
  res = wm.autoConnect("PC_Mon", "12345678"); // password protected ap

  if (!res)
  {
    Serial.println("Failed to connect");
    ESP.restart();
  }
  //----------------------------

  client.enableDebuggingMessages();                        // Enable debugging messages sent to serial output
  client.enableHTTPWebUpdater();                           // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password").
  //----------------------------

  ESP.wdtEnable(5000); // Set a 5s watchdog
}

//-----------------------------------------------------------
void loop() {
  ESP.wdtFeed();

  client.loop(); // MQTT loop
}

//---------------------------------------------------------------
void onConnectionEstablished()
{
  client.subscribe(SUB_TOPIC, [](const String & payload) {
    drawStat(payload);
  });
}

//---------------------------------------------------------------
void drawStat(String payload) // display status data
{
  display.clear();

  deserializeJson(doc,payload);
  JsonObject obj = doc.as<JsonObject>();
  String cpu =obj["cpu"];
  String mem =obj["mem"];
  String ip =obj["ip"];

  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(Coming_Soon_Regular_20);
  display.drawString(0, 0, "CPU: "+cpu + "%");
  display.setFont(Coming_Soon_Regular_20);
  display.drawString(0, 21, "MEM: "+mem + "%");
  display.setFont(Coming_Soon_Regular_16);
  display.drawString(0, 42, "IP: " + ip);
  // write the buffer to the display
  display.display();
}

//-----------------------------------------------------------
/*void drawBoot() // Boot OLED display
{
  display.clear();
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(Coming_Soon_Regular_20);
  display.drawString(24, 24, "Booting");
  // write the buffer to the display
  display.display();
}*/

//---------------------------------------------------------------
void drawConf() // WiFi config OLED display
{
  display.clear();
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(Coming_Soon_Regular_20);
  display.drawString(12, 24, "WiFi Conf");
  // write the buffer to the display
  display.display();
}